package mvc.framework;

import mvc.handlers.*;

import java.util.Map;
import java.util.HashMap;

/**
 * Factory per la generazione dell'opportuno RequestHandler per la richiesta
 * 
 * @author Grillo
 */
public class RequestHandlerFactory {
    private static Map<String, IRequestHandler> handlers = new HashMap<String, IRequestHandler>();
    
    public static final String ACTION_PARAM = "action";
    
    public static IRequestHandler getRequestHandler(DialogHandler dialogHandler) throws Exception {
        if (handlers.size() == 0) { 
            initializeHandlers(); 
            if (handlers.size() == 0) throw new Exception(" # ATTENZIONE! La Factory delle azioni è vuota!");
        }                
        String action = getAction(dialogHandler);
        IRequestHandler requestHandler = null;
        
        try {
            requestHandler = handlers.get(action);
            requestHandler = requestHandler.clone(dialogHandler);
        } catch (CloneNotSupportedException cnse) {
             throw new Exception(" # ATTENZIONE! '" + action + "' non supportata!", cnse);
        } catch (NullPointerException cnse) {
             throw new Exception(" # ATTENZIONE! '" + action + "' non supportata!", cnse);
        }
        
        return requestHandler;
    }
    
    public static void attachHandler(IRequestHandler requestHandler) {
        handlers.put(requestHandler.getActionName(), requestHandler);
    } 
    
    public static void detachHandler(IRequestHandler requestHandler) {
        handlers.remove(requestHandler);
    }
    
    // ########## Metodi Privati ##########
    
    private static String getAction(DialogHandler dHandler) {
        String action = dHandler.getParameter(ACTION_PARAM);
        if (action == null) 
            action = new HomeHandler(dHandler).getActionName(); // Impostazione pagina di default
        return action;
    }
    
    private static void initializeHandlers() {
        // Caricamento della lista di azioni gestite dal controller
        attachHandler(new HomeHandler(null));
        attachHandler(new LoginHandler(null));
        attachHandler(new LogoutHandler(null));
        attachHandler(new ShowProfileHandler(null));
        attachHandler(new AddStudenteHandler(null));
        attachHandler(new AddEsameHandler(null));
        attachHandler(new RemoveEsameHandler(null));
        attachHandler(new ListaEsamiHandler(null));
        attachHandler(new ListaStudentiHandler(null));
        attachHandler(new ListaDocentiHandler(null));
    }
}
